import routes from "../route/route";
import mongodbHandle from '../handle/mongodbHandle';
import rankHandle from '../handle/rankHandle';
const jwt = require('jsonwebtoken');
var ObjectId = require('mongodb').ObjectId;
import * as moment from 'moment'
import app from '../app';
import utils from '../core/utils';
import redisHandle from 'src/handle/redisHandle';
// import route from "js/route/route";
import * as request from 'request'
import { base64 } from '../core/enco';

var utility = require("utility");

function getResData(data) {
    data = JSON.stringify(data)
    if (app.env == 'pro' || app.env == "demo") {
        data = base64.encode(data)
    }
    return data
}

routes.setUserNotLogin('adminRegister', [
    ['name', 'string'],
    ['pwd', 'string']
], async (msg, session,) => {
    let name = msg.name
    let pwd = msg.pwd
    if (app.env == "adminDemo") {
        let doc = await mongodbHandle.userAdminDao.findOne({ name, pwd })

        if (doc) {
            return { err: 1 }
        } else {
            await mongodbHandle.userAdminDao.newAndSave(name, pwd)
            return { err: 0 }
        }
    } else {
        return { err: 2 }
    }

})

routes.setUserNotLogin('adminLogin', [
    ['name', 'string'],
    ['pwd', 'string']
], async (msg, session,) => {
    let name = msg.name
    let pwd = msg.pwd

    let doc = await mongodbHandle.userAdminDao.findOne({ name, pwd })
    if (doc) {
        let token = jwt.sign({
            name: name,
            pwd: pwd
        }, "secretkey", {
            expiresIn: '2day'
        })
        return { err: 0, data: token }
    } else {
        return { err: 1 }
    }
})

routes.setUserNotLogin('getPlayerBaseInfo', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let id
    try {
        id = ObjectId(msg.pID)
    } catch (error) {
        return { err: 0, code: 1 }
    }
    let doc = await mongodbHandle.playerDao.findOne({
        _id: id
    })
    if (doc) {
        return {
            err: 0, data: {
                name: doc.name,
                currentServerID: doc.currentServerID,
                chargeMoney: doc.chargeMoney,
            }
        }
    } else {
        return { err: 0, code: 1 }
    }
})

// const Token = "Vo1NIIzyAEQg43vo4InPsq4r0u471viO"
// routes.setUserNotLogin('pay', [
//     ['pID', 'string'],
//     ['index', 'number'],
//     ['type', 'number']
// ], async (msg, session, cb) => {
//     let {
//         pID,
//         index,
//         type
//     } = msg
//     let chargetType
//     if (index == 13) {
//         index = 14
//     }
//     let chargetTypes = {
//         1: { name: 'month', money: 30.00 },
//         2: { name: 'season', money: 80.00 },
//         3: { name: 'halfyear', money: 150.00 },
//         4: { name: 'fantasy', money: 9.00 },
//         5: { name: 'fantasy5', money: 45.00 },
//         6: { name: 'fantasy10', money: 90.00 },
//         7: { name: 'fantasy30', money: 270.00 },
//         8: { name: 'fantasy50', money: 450.00 },
//         11: { name: 'materials1', money: 9.00 },
//         12: { name: 'materials5', money: 45.00 },
//         13: { name: 'materials10', money: 90.00 },
//         14: { name: 'materials30', money: 270.00 },
//         15: { name: 'materials50', money: 450.00 },
//         21: { name: 'diamond', money: 9.00 },
//         22: { name: 'diamond5', money: 45.00 },
//         23: { name: 'diamond10', money: 90.00 },
//         24: { name: 'diamond30', money: 270.00 },
//         25: { name: 'diamond50', money: 450.00 },
//         26: { name: 'material', money: 9.00 },
//         27: { name: 'material5', money: 45.00 },
//         28: { name: 'material10', money: 90.00 },
//         29: { name: 'material30', money: 270.00 },
//         30: { name: 'material50', money: 450.00 },
//     }
//     chargetType = chargetTypes[index]
//     if (!chargetType) {
//         return { err: 1 }
//     }
//     if (type !== 1 && type !== 2) {
//         return { err: 2 }
//     }
//     let orderID = utils.randomString(16)
//     // let goodsname = Goodsname[index]
//     let player = await mongodbHandle.playerDao.findOne({
//         _id: ObjectId(msg.pID)
//     })
//     if (!player) {
//         return { err: 2 }
//     }
//     // let str = `${goodsname}${istype}${app.config.pay_notify_url}${orderID}${orderuid}${money}${app.config.pay_return_url}${Token}${Uid}`
//     // var md5Value = utility.md5(str);
//     type = type == 1 ? "alipay" : "wxpay"
//     let money = chargetType.money
//     let pid = 265199
//     let name = chargetType.name
//     let str = `money=${money}&name=${name}&notify_url=${app.config.pay_notify_url}&out_trade_no=${orderID}&pid=${pid}&return_url=${app.config.pay_return_url}&type=${type}${Token}${Token}`
//     var md5Value = utility.md5(str);
//     await mongodbHandle.chargeDao.newAndSave(orderID, player.uID, pID, money, index)
//     return {
//         err: 0,
//         data: {
//             pid: pid,
//             out_trade_no: orderID,
//             money: money,
//             type: type,
//             notify_url: app.config.pay_notify_url,
//             return_url: app.config.pay_return_url,
//             name: chargetType.name,
//             // sitename: '奇幻冒险',
//             sign: md5Value
//         }
//     }

// })

routes.setUserNotLogin('giftBuyTims', [
    ['pID', 'string'],
], async (msg, session) => {
    let {
        pID
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(pID),
    })
    if (doc) {
        return {
            err: 0, data: {
                giftTime: doc.giftTime || moment().startOf('day').valueOf(),
                giftBuyTims: doc.giftBuyTims || 0
            }
        }
    }
    return {
        err: 0, data: {
            giftTime: 0,
            giftBuyTims: 0
        }
    }
})

routes.setUserNotLogin('createNightReward', [
], async (msg, session) => {
    rankHandle.createNightProgressRankReward()
    return {
        err: 0
    }
})



routes.setLogin('getUserList', [
    ['page', 'number'],
    ['pageSize', 'number']
], async (msg, session, cb) => {
    let {
        page,
        pageSize
    } = msg
    let query = {}
    let count = await mongodbHandle.userDao.count(query)
    let docs = await mongodbHandle.userDao.findByPage(query, (page - 1) * pageSize, pageSize)
    return { err: 0, data: { data: docs, total: count } }
})

routes.setLogin('getRank', [
    ['serverID', 'number'],
], async (msg, session, cb) => {
    let {
        serverID
    } = msg

    let docs = await mongodbHandle.playerDao.findByPageAndSort({
        currentServerID: Number(msg.serverID),
        "totalPower": {
            $gt: 500
        },
    }, {
        "totalPower": -1
    }, 0, 50)
    let datas = []
    docs.forEach((doc, i) => {
        let data = {
            rank: i + 1,
            id: doc.id,
            pID: doc._id.toString(),
            value: doc.totalPower,
            name: doc.playerData ? doc.playerData.playerName : '',
        }
        datas.push(data)
    })
    return { err: 0, data: datas }
})


routes.setLogin('getTagPlayerList', [
    ['serverID', 'number'],
], async (msg, session, cb) => {
    let {
        serverID,
    } = msg
    let query = {
        currentServerID: serverID,
        $or: [
            { isTag: true },
            { 'playerData.info.cheat': { $gte: 0 } }
        ],
    }
    let sortQuery = {
        totalPower: -1,
        loginTime: -1

    }
    let page = 1
    let pageSize = 50
    let serverDoc = await mongodbHandle.serverDao.findOne({ serverID: serverID })
    let docs = await mongodbHandle.playerDao.findByPageAndSort(query, sortQuery, (page - 1) * pageSize, pageSize)
    for (let i = 0; i < docs.length; i++) {
        let item = docs[i]
        item.Diamond = item.playerData.itemInfo?.diamond || 0
        item.Gold = item.playerData.itemInfo?.gold || 0
        item.useDiamond = item.playerData.itemInfo?.usedItemStat?.diamond || 0
        item.useGold = item.playerData.itemInfo?.usedItemStat?.gold || 0
        item.vip = item.playerData.baseInfo.vip || 0
        item.deep = item.playerData.deepInfo.progress || 0
        item.progress = utils.getMapMax(item.playerData.baseInfo.mapProgressMax) || { mapID: 100001, floor: 1 }
        item.serverName = serverDoc?.name
        item.cheatTimes = item.playerData.info ? item.playerData.info['cheat'] || 0 : 0
        if (item.isTag) {
            let message = await mongodbHandle.cheatDao.findByPageAndSort({ uID: item.uID, itemType: { $ne: null } }, { createTime: -1 }, 0, 50)
            let lastOne = {}
            if (message.length > 0) {
                lastOne = message[message.length - 1]
            }
            item.tagMessage = lastOne
        }
        delete item.playerData
        delete item.saveData
        delete item.saveKey
        delete item.itemInfo

        let userData = await mongodbHandle.userDao.findOne({ _id: ObjectId(item.uID) })
        if (userData) {
            item.uHidePay = userData.hidePay
            item.userName = userData.name
        }
    }
    return { err: 0, data: { data: docs } }
})

routes.setLogin('getPlayerListByName', [
    ['name', 'string'],
], async (msg, session, cb) => {
    let {
        name
    } = msg
    let query = {
        name: name
    }
    let docs = await mongodbHandle.playerDao.find(query)
    for (let i = 0; i < docs.length; i++) {
        let item = docs[i]
        item.Diamond = item.playerData.BasicInfo.Diamond
        item.Gold = item.playerData.BasicInfo.Gold
        item.PlayerLvl = []
        if (item.playerData.Team) {
            item.playerData.Team.forEach(e => {
                if (e) {
                    item.PlayerLvl.push(e.Lvl)
                }
            })
        }

        delete item.playerData
    }
    return { err: 0, data: docs }
})

routes.setLogin('getPlayerList', [
    ['page', 'number'],
    ['pageSize', 'number'],
    ['serverID', 'number', false],
    ['type', 'string', false]
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        totalPower,
        serverID,
        type
    } = msg
    let query = {
        currentServerID: serverID,
        'itemInfo.diamond': {
            $gte: 100
        },
        'itemInfo.gold': {
            $gte: 100000
        }
    }
    let sortQuery
    if (type == 'progress') {
        sortQuery = {
            'playerData.adventureInfo.totalFloor': -1
        }
    } else if (type == 'deep') {
        sortQuery = {
            'playerData.deepInfo.progress': -1
        }
    } else {
        sortQuery = {
            totalPower: -1
        }
    }
    page = 1
    pageSize = 50
    let count = await mongodbHandle.playerDao.count(query)
    let docs = await mongodbHandle.playerDao.findByPageAndSort(query, sortQuery, (page - 1) * pageSize, pageSize)
    let serverDoc = await mongodbHandle.serverDao.findOne({ serverID: serverID })
    for (let i = 0; i < docs.length; i++) {
        let item = docs[i]
        item.Diamond = item.playerData.itemInfo?.diamond || 0
        item.Gold = item.playerData.itemInfo?.gold || 0
        item.useDiamond = item.playerData.itemInfo?.usedItemStat?.diamond || 0
        item.useGold = item.playerData.itemInfo?.usedItemStat?.gold || 0
        item.vip = item.playerData.baseInfo.vip || 0
        item.deep = item.playerData.deepInfo.progress || 0
        item.progress = utils.getMapMax(item.playerData.baseInfo.mapProgressMax) || { mapID: 100001, floor: 1 }
        item.serverName = serverDoc?.name
        item.cheatTimes = item.playerData.info ? item.playerData.info.cheat || 0 : 0
        delete item.playerData
        delete item.saveData
        delete item.saveKey
        delete item.itemInfo

        let userData = await mongodbHandle.userDao.findOne({ _id: ObjectId(item.uID) })
        if (userData) {
            item.uHidePay = userData.hidePay
            item.userName = userData.name
        }
    }
    return { err: 0, data: { data: docs, total: count } }
})

routes.setLogin('getPlayer', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(msg.pID)
    })
    if (doc) {
        doc.Gold = doc.playerData.BasicInfo.Gold
        doc.Diamond = doc.playerData.BasicInfo.Diamond
        delete doc.playerData
        let userData = await mongodbHandle.userDao.findOne({
            _id: ObjectId(doc.uID)
        })
        doc.uHidePay = userData.hidePay
        doc.userName = userData.name
        doc.pwd = userData.pwd
        return { err: 0, data: doc }
    } else {
        return { err: 0, code: 1 }
    }
})

routes.setLogin('switchXianYu', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let {
        pID,
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        let day = moment().startOf('day').valueOf()
        if (myData.unStatDay == day) {
            day = 0
        }
        let xianyu = myData.xianyu || false
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                xianyu: !xianyu
            }
        })
        return {
            err: 0,
        }
    }
    return { err: 0, code: 0 }
})

routes.setLogin('switchStat', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let {
        pID,
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        let day = moment().startOf('day').valueOf()
        if (myData.unStatDay == day) {
            day = 0
        }
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                unStatDay: day
            }
        })
        return {
            err: 0,
            code: day
        }
    }
    return { err: 0, code: 0 }
})

routes.setLogin('switchBan', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let {
        pID,
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    let cheat = myData.cheat
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                cheat: !cheat
            }
        })
        //
        if (cheat) {
            await mongodbHandle.versionCheatDao.remove({ pID: pID })
        }
        return {
            err: 0,
            code: !cheat
        }
    }
    return { err: 0, code: cheat }
})

routes.setLogin('getPlayerInfo', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(msg.pID)
    })
    if (doc) {
        doc.gold = doc.playerData.baseInfo.gold
        doc.money = doc.playerData.baseInfo.money
        delete doc.playerData
        let userData = await mongodbHandle.userDao.findOne({
            _id: ObjectId(doc.uID)
        })
        doc.uHidePay = userData.hidePay
        doc.userName = userData.name
        doc.pwd = userData.pwd
    }
    return { err: 0, data: doc }
})

routes.setLogin('getPlayerInfoByid', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        id: msg.id
    })
    if (doc) {
        delete doc.playerData
        let userData = await mongodbHandle.userDao.findOne({
            _id: ObjectId(doc.uID)
        })
        doc.uHidePay = userData.hidePay
        doc.userName = userData.name
        doc.pwd = userData.pwd
    }
    return { err: 0, data: doc }
})

routes.setLogin('getPlayerBak', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerBakDao.findOne({
        pID: msg.pID
    })
    return { err: 0, data: doc }
})


routes.setLogin('setPlayerCheat', [
    ['pID', 'string'],
    ['cheat', 'boolean']
], async (msg, session) => {
    let {
        pID,
        cheat
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                cheat: cheat
            }
        })
    }
    return { err: 0 }
})

routes.setLogin('playerModify', [
    ['pID', 'string'],
], async (msg, session) => {
    let {
        pID,
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            modify: 'init',
            modifyTimes: 0,
        }
    })
    return {
        err: 0
    }
})

routes.setLogin('addMoney', [
    ['pID', 'string'],
    ['amount', 'number'],
], async (msg, session) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            chargeMoney: (doc.chargeMoney || 0) + amount
        }
    })
    return {
        err: 0
    }
})

routes.setLogin('buyVip', [
    ['pID', 'string'],
    ['amount', 'number'],
], async (msg, session) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    let vipTime = (doc.vipTime || new Date().getTime())
    if (vipTime < moment().valueOf()) {
        vipTime = moment().valueOf()
    }
    vipTime += amount * 24 * 60 * 60 * 1000
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            vipTime: vipTime
        }
    })
    return {
        err: 0
    }
})

routes.setLogin('changepwd', [
    ['name', 'string'],
    ['oldPwd', 'string'],
    ['pwd', 'string'],
], async (msg, session) => {
    let {
        name,
        amount
    } = msg
    let doc = await mongodbHandle.userDao.findOne({ name: name })
    if (!doc) {
        return { err: 1 }
    }
    if (doc.pwd == msg.oldPwd) {
        await mongodbHandle.userDao.updateOne({
            name: name
        }, {
            $set: {
                pwd: msg.pwd
            }
        })
        return {
            err: 0
        }
    } else {
        return {
            err: 1
        }
    }

})

routes.setLogin('addVipAmount', [
    ['pID', 'string'],
    ['amount', 'number'],
], async (msg, session, cb) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            chargeMoney: (doc.chargeMoney || 0) + 10 * amount
        }
    })
    mongodbHandle.adminRecordDao.newAndSave(session.name, "buyVip", JSON.stringify({ pID, amount }))
    return {
        err: 0
    }
})

routes.setLogin('sendGift', [
    ['id', 'string'],
    ['title', 'string', false],
    ['gift', 'any'],
], async (msg, session, cb) => {
    let {
        id,
        gift,
        title
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ id: id })
    if (!doc) {
        return { err: 1 }
    }
    let senfTitle = title || '奖励礼包'
    if (gift && gift.length > 0) {
        for (let i = 0; i < gift.length; i++) {
            let g = gift[i];
            if (g) {
                let itemID = g[0]
                if (itemID == 'vipTime') {
                    let vipTime = (doc.vipTime || new Date().getTime())
                    if (vipTime < moment().valueOf()) {
                        vipTime = moment().valueOf()
                    }
                    vipTime += g[1]
                    await mongodbHandle.playerDao.updateOne({
                        id: doc.id
                    }, {
                        $set: {
                            vipTime: vipTime
                        }
                    })
                } else if (itemID == 'longVip') {
                    await mongodbHandle.playerDao.updateOne({
                        id: doc.id
                    }, {
                        $set: {
                            longVip: true
                        }
                    })
                }
            }
        }
    }
    await mongodbHandle.mailDao.newAndSave(doc._id.toString(), senfTitle, gift, null)
    // if (type == 1) {
    //     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 100, 0)
    // } else if (type == 2) {
    //     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 500, 0)
    // } else if (type == 3) {
    //     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 0, 100000)
    // }
    return {
        err: 0
    }
})

routes.setLogin('sendGiftByServerId', [
    ['serverID', 'any'],
    ['title', 'string', false],
    ['gift', 'any'],
], async (msg, session, cb) => {
    let {
        serverID,
        gift,
        title
    } = msg
    let doc = await mongodbHandle.serverDao.findOne({
        serverID: Number(serverID)
    })
    if (!doc) {
        return { err: 1 }
    }
    let senfTitle = title || '补偿礼包'
    let count = await mongodbHandle.playerDao.count({
        currentServerID: Number(serverID)
    })
    let pageAmount = 300, page = 0, totalPage = Math.floor(count / 300) || 1
    for (let i = 0; i < totalPage; i++) {
        let docs = await mongodbHandle.playerDao.findByPageAndSort({
            currentServerID: Number(serverID)
        }, { loginTime: -1 }, page, pageAmount)
        // if (docs.length > 0) {
        //     for (let j = 0; j < docs.length; j++) {
        //         let doc = docs[j];
        //         await mongodbHandle.mailDao.newAndSave(doc._id.toString(), title, gift, null)
        //     }
        // }
        page += 1
    }
    // if (type == 1) {
    //     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 100, 0)
    // } else if (type == 2) {
    //     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 500, 0)
    // } else if (type == 3) {
    //     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 0, 100000)
    // }
    return {
        err: 0
    }
})

// routes.setLogin('addDiamond', [
//     ['pID', 'string'],
//     ['value', 'number'],
// ], async (msg, session, cb) => {
//     let {
//         pID,
//         value
//     } = msg
//     let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
//     if (!doc) {
//         return { err: 1 }
//     }
//     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, value, 0)
//     return {
//         err: 0
//     }
// })

// routes.setLogin('addGold', [
//     ['pID', 'string'],
//     ['value', 'number'],
// ], async (msg, session, cb) => {
//     let {
//         pID,
//         value
//     } = msg
//     let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
//     if (!doc) {
//         return { err: 1 }
//     }
//     await mongodbHandle.mailDao.newAndSave(pID, '奖励礼包', null, 0, value)
//     return {
//         err: 0
//     }
// })

// routes.setLogin('addArenaPoint', [
//     ['pID', 'string'],
//     ['value', 'number'],
// ], async (msg, session, cb) => {
//     let {
//         pID,
//         value
//     } = msg
//     let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
//     if (!doc) {
//         return { err: 1 }
//     }
//     await mongodbHandle.mailDao.newAndSave(pID, '奖励', null, 0, 0, 0, value)
//     return {
//         err: 0
//     }
// })

routes.setLogin('addDiamondAllServer', [
    ['name', 'string'],
    ['value', 'number'],
    ['gold', 'number'],
    ['items', 'array', false],
    ['arenaPoint', 'number', false],
    ['serverID', 'number', false],
    ['startime', 'number', false],
    ['endtime', 'number', false],
], async (msg, session, cb) => {
    let { name, value, items, arenaPoint, gold, serverID } = msg
    let docs = await mongodbHandle.serverDao.find({
        active: true
    })

    let serverList = {}
    if (serverID) {
        serverList[serverID] = true
    } else {
        for (let i = 0; i < docs.length; i++) {
            let serverID = docs[i].newServerID
            serverList[serverID] = true
        }
    }
    let servers: number[] = []
    Object.keys(serverList).forEach((item, i) => {
        servers[i] = Number(item)
    })
    let time = moment().add(-2, 'days').valueOf()
    for (let i = 0; i < servers.length; i++) {
        let serverID = servers[i]
        let page = 0
        let length = 100
        let players = []
        while (length >= 100) {
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "loginTime": {
                    $gt: time
                },
            }, { loginTime: 1 }, page * 100, 100)
            length = docs.length
            page += 1
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let pID = doc._id.toString()
                players.push(pID)
            }
        }
        for (let i = 0; i < players.length; i++) {
            let pID = players[i]
            // await mongodbHandle.mailDao.newAndSave(pID, `${name}`, items, value, gold, 0, arenaPoint)
            if (i % 100 == 0) {
                await utils.setTimeout(50)
                console.log(i)
            }
        }
    }
    return {
        err: 0
    }
})


routes.setLogin('setGameClientData', [
    ['key', 'string'],
    ['value', 'string', false],
], async (msg, session, cb) => {
    let { key, value, env } = msg
    let str = await redisHandle.get(app.config.gameName + 'gameSet')
    let data = {}
    if (str) {
        try {
            data = JSON.parse(str)
        } catch (e) {
            data = {}
        }
    }
    if (value && value.length !== 0) {
        data[key] = value
    } else {
        delete data[key]
    }
    await redisHandle.set(app.config.gameName + 'gameSet', JSON.stringify(data))


    return {
        err: 0,
        data: data
    }
})

routes.setLogin('setPlayeHidePay', [
    ['uID', 'string'],
    ['pID', 'string'],
    ['value', 'number', false],
], async (msg, session, cb) => {
    let { pID, value, uID } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.playerDao.updateOne({ _id: ObjectId(pID) },
        { $set: { hidePay: value } })

    let uData = await mongodbHandle.userDao.findOne({ _id: ObjectId(uID) })
    if (uData) {
        await mongodbHandle.userDao.updateOne({
            _id: ObjectId(uID)
        }, {
            $set: {
                hidePay: value
            }
        })
    }
    return {
        err: 0
    }
})

routes.setLogin('setServerState', [
    ['serverState', 'number'],
    ['stateText', 'string']
], async (msg, cb) => {
    app.serverState = msg.serverState
    app.stateText = msg.stateText || "服务器在维护中"
    await mongodbHandle.gameDao.updateOne({
        index: 1
    }, {
        $set: {
            serverState: app.serverState,
            stateText: app.stateText
        }
    });
    request.post({
        url: `http://127.0.0.1:${app.config.serverMasterPort}/masterapp/api/setServerState`,
        headers: {
            "testclient": "cheat123",
        },
        body: getResData({ serverState: app.serverState, stateText: app.stateText }),
    },
        function (error, response, body) {
            console.log(error, body)
        }
    );
    return { err: 0 }
})

routes.setLogin('compensateVipAllServer', [

], async (msg, session, cb) => {
    let docs = await mongodbHandle.serverDao.find({
        active: true
    })
    let serverList = {}
    for (let i = 0; i < docs.length; i++) {
        let serverID = docs[i].newServerID
        serverList[serverID] = true
    }
    let servers: number[] = []
    Object.keys(serverList).forEach((item, i) => {
        servers[i] = Number(item)
    })
    let time = moment().add(-1, 'days').valueOf()
    for (let i = 0; i < servers.length; i++) {
        let serverID = servers[i]
        let page = 0
        let length = 200
        while (length >= 200) {
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "vipTotal": {
                    $gt: 0
                },
            }, { loginTime: 1 }, page * 200, 200)
            length = docs.length
            page += 1
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let pID = doc._id.toString()
                let vipTotal = doc.vipTotal
                // let diamond = 0
                // diamond += Math.floor(vipTotal / 6) * 2100
                // diamond += Math.floor(vipTotal % 6 / 3) * 1000
                // diamond += Math.floor(vipTotal % 6 % 3) * 300
                // await mongodbHandle.mailDao.newAndSave(pID, `会员赠送钻石补偿`, null, diamond, 0)
                // if (vipTotal > 24) {
                //     let amount = vipTotal - 24
                //     diamond += Math.floor(amount / 6) * 2100 * 0.5
                //     diamond += Math.floor(amount % 6 / 3) * 1000 * 0.5
                //     diamond += Math.floor(amount % 6 % 3) * 300 * 0.5

                // }
                if (vipTotal > 0 && vipTotal <= 24) {
                    let diamond = vipTotal * 750
                    // await mongodbHandle.mailDao.newAndSave(pID, `会员赠送钻石调整补偿`, null, diamond, 0)
                    if (i % 20 == 0) {
                        await utils.setTimeout(150)
                    }
                }
            }
        }
    }
    return {
        err: 0
    }
})

routes.setLogin('addItem', [
    ['pID', 'string'],
    ['itemID', 'any'],
    ['value', 'number'],
], async (msg, session, cb) => {
    let {
        pID,
        itemID,
        value
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.mailDao.newAndSave(pID, '礼包', [[itemID, value]], null)
    return {
        err: 0
    }
})

routes.setLogin('addItem2', [
    ['pID', 'string'],
    ['items', 'object'],
], async (msg, session, cb) => {
    let {
        pID,
        items
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.mailDao.newAndSave(pID, '礼包', null, items)
    return {
        err: 0
    }
})

routes.setLogin('addGiftByID', [
    ['id', 'string']
], async (msg, session, cb) => {
    let { id } = msg
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (!doc) {
        return { err: 1 }
    }
    let idStr = utils.randomString(12)
    await mongodbHandle.giftListDao.newAndSave(idStr, id)
    return {
        err: 0,
        data: idStr,
    }
})

routes.setLogin('creatGifts', [
    ['id', 'string'],
    ['amount', 'number']
], async (msg, session, cb) => {
    let { id, amount } = msg
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (!doc) {
        return { err: 1 }
    }
    let ids = []
    for (let i = 0; i < amount; i++) {
        let idStr = utils.randomString(12)
        await mongodbHandle.giftListDao.newAndSave(idStr, id)
        ids.push(idStr)
    }
    return {
        err: 0,
        data: ids,
    }
})

routes.setLogin('addGift', [
    ['id', 'string'],
    ['name', 'string'],
    ['items1', 'array', false],
    ['items2', 'array', false],
    ['endTime', 'number'],
    ['startTime', 'number'],
    ['multiple', 'boolean', false]
], async (msg, session, cb) => {
    let { id, name, diamond, items2, items1, endTime, startTime, multiple } = msg
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (doc) {
        return { err: 1 }
    }
    await mongodbHandle.giftDao.newAndSave(id, name, items1, items2, startTime, endTime, multiple)
    return {
        err: 0
    }
})

routes.setLogin('giftList', [

], async (msg, session, cb) => {
    let docs = await mongodbHandle.giftDao.find({})
    return {
        err: 0, data: docs
    }
})

// userChargeData
routes.setLogin('userChargeData', [

], async (msg, session, cb) => {
    let { id, pID, serverID } = msg
    let query = {}
    if (id) {
        query['id'] = id
    } else if (pID) {
        query['uID'] = pID
    }
    if (serverID) {
        query['currentServerID'] = serverID
        query['itemInfo'] = {
            gold: {
                $gte: 100000000
            },
            diamond: {
                $gte: 10000
            }
        }
    }
    let docs = await mongodbHandle.playerDao.findByPageAndSort(query, {
        registerTime: -1,
    }, 0, 50)
    let data = []
    if (docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
            let doc = docs[i];
            let d = {
                id: doc.id,
                uID: doc.uID,
                pID: doc._id.toString(),
                vip: doc.playerData.baseInfo.vip || 0,
                diamond: doc.playerData.itemInfo?.diamond || 0,
                gold: doc.playerData.itemInfo?.gold || 0,
                chargeMoney: doc.chargeMoney,
                itemInfo: doc.itemInfo,
                cheat: doc.cheat,
            }
            data.push(d)
        }
    }
    return {
        err: 0, data
    }
})

routes.setLogin('giftActive', [
    ['id', 'string'],
    ['active', 'boolean'],
], async (msg, session, cb) => {
    let { id, active } = msg
    await mongodbHandle.giftDao.updateOne({ id: id }, { $set: { active: active } })
    return {
        err: 0
    }
})

routes.setLogin('delGift', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let { id } = msg
    await mongodbHandle.giftDao.remove({ id: id })
    return {
        err: 0
    }
})

routes.setLogin('getAllServerList', [
    ['page', 'number'],
    ['pageSize', 'number']
], async (msg, session, cb) => {
    let {
        page,
        pageSize
    } = msg
    let query = {}
    let count = await mongodbHandle.serverDao.count(query)
    let docs = await mongodbHandle.serverDao.findByPage(query, (page - 1) * pageSize, pageSize)
    return {
        err: 0, data: {
            data: docs,
            total: count
        }
    }
})



//添加服务器
routes.setLogin('addServer', [
    ['serverID', 'number'],
    ['name', 'string'],
    ['time', 'number']
], async (msg, session, cb) => {
    let {
        serverID,
        name,
        time
    } = msg
    let doc = await mongodbHandle.serverDao.findOne({
        serverID: serverID
    })
    if (!doc) {
        mongodbHandle.serverDao.newAndSave(serverID, name, time)
        return {
            err: 0
        }
    }
    return {
        err: 1
    }
})

//添加服务器
routes.setLogin('updateServer', [
    ['id', 'string'],
    ['serverID', 'number'],
    ['name', 'string']
], async (msg, session, cb) => {
    let {
        id,
        serverID,
        name
    } = msg
    mongodbHandle.serverDao.updateOne({
        _id: ObjectId(id)
    }, {
        $set: {
            serverID: serverID,
            name: name
        }
    })
})

//合并服务器
routes.setLogin('mergeServer', [
    ['server1', 'number'],
    ['server2', 'number']
], async (msg, session, cb) => {

})

//开关服务器
routes.setLogin('activationServer', [
    ['serverID', 'number'],
], async (msg, session, cb) => {
    let {
        serverID
    } = msg

    let doc = await mongodbHandle.serverDao.findOne({
        serverID: serverID
    })
    if (doc) {
        doc.active = !doc.active
        mongodbHandle.serverDao.updateOne({
            serverID: serverID
        }, { $set: { active: doc.active } })
        return {
            err: 0
        }
    }
    return {
        err: 1
    }
})

//充值
routes.setLogin('chargeList', [
    ['id', 'string', false],
    ['startTime', 'number', false],
    ['endTime', 'number', false]
], async (msg, session, cb) => {
    let {
        id,
        startTime,
        endTime
    } = msg
    let query = { isPay: true }
    if (id) {
        query['pID'] = id
    }
    if (startTime) {
        query['time'] = {
            $gte: startTime,
            $lte: endTime
        }
    }
    let playerDoc = await mongodbHandle.playerDao.findOne({ id: id })
    if (!playerDoc) {
        return {
            err: 0,
            data: { list: [], totalCharge: 0 }
        }
    }
    console.log(id, 111)
    let docs = await mongodbHandle.chargeDao.findAndSort(query, {
        time: -1
    })
    let data = []
    let totalCharge = 0
    for (let i = 0; i < docs.length; i++) {
        let doc = docs[i];
        let d = {
            id: doc.pID,
            uID: playerDoc.uID,
            chargeMoney: doc.amount * 20,
            time: doc.time,
            day: doc.day,
            vip: playerDoc.playerData.baseInfo.vip,
            name: playerDoc.playerData.playerName
        }
        totalCharge += d.chargeMoney
        data.push(d)
    }
    return {
        err: 0, data: { list: data, totalCharge }
    }
})


routes.setLogin('testRank', [
], async (msg, session, cb) => {
    rankHandle.createPowerRankReward()
    rankHandle.createArenaRankReward()
    if (app.env == 'adminDemo') {
        rankHandle.createMapProgressRankReward('demo')
        rankHandle.createWorldBossRankReward('demo')
    } else if (app.env == 'adminPro') {
        rankHandle.createMapProgressRankReward('pro')
        rankHandle.createWorldBossRankReward('pro')
    } else {
        rankHandle.createMapProgressRankReward('dev')
        rankHandle.createWorldBossRankReward('dev')
    }

    return {
        err: 0,
    }
})

routes.setLogin('testRank2', [
    ['serverID', 'number'],
    ['type', 'number']
], async (msg, session, cb) => {
    let { serverID, type } = msg
    if (type == 1) {
        rankHandle.createPowerRankRewardByServerID(serverID)
        return {
            err: 0,
        }
    }

    if (type == 2) {
        rankHandle.createArenaRankRewardByServerID(serverID)
        return {
            err: 0,
        }
    }

    if (type == 3) {
        if (app.env == 'adminDemo') {
            rankHandle.createMapProgressRankRewardByServerID('demo', serverID)
        } else if (app.env == 'adminPro') {
            rankHandle.createMapProgressRankRewardByServerID('pro', serverID)
        } else {
            rankHandle.createMapProgressRankRewardByServerID('dev', serverID)
        }
        return {
            err: 0,
        }
    }

    if (type == 4) {
        if (app.env == 'adminDemo') {
            rankHandle.createWorldBossRankRewardByServerID('demo', serverID)
        } else if (app.env == 'adminPro') {
            rankHandle.createWorldBossRankRewardByServerID('pro', serverID)
        } else {
            rankHandle.createWorldBossRankRewardByServerID('dev', serverID)
        }
        return {
            err: 0,
        }
    }

})


//充值
routes.setNotLogin('charge', [
    ['trade_status', 'string'],
    ['pid', 'string', false],
    ['out_trade_no', 'string'],
    ['trade_no', 'string', false],
    ['money', 'string', false],
    ['type', 'string', false],
    ['name', 'string', false],
    ['sign', 'string', false],
    ['sign_type', 'string', false],
], async (msg, session, cb) => {
    let {
        trade_status, pid, out_trade_no, trade_no, money, type, name, sign, sign_type
    } = msg
    if (!trade_status) {
        return { err: 1 }
    }
    let doc = await mongodbHandle.chargeDao.findOne({ orderID: out_trade_no })
    if (!doc) {
        return { err: 2 }
    }
    if (doc.isPay) {
        return { err: 3 }
    }
    await mongodbHandle.chargeDao.updateOne({ orderID: out_trade_no }, {
        $set: {
            isPay: true,
        }
    })

    //********** */
    if (doc.productID == 1 || doc.productID == 2 || doc.productID == 3) {
        let player = await mongodbHandle.playerDao.findOne({ _id: ObjectId(doc.pID) })
        let time = player.vipTime
        let vipTotal = player.vipTotal
        if (!vipTotal) {
            vipTotal = 0
        }
        let amount = 1
        if (doc.productID == 1) {
            amount = 1
        } else if (doc.productID == 2) {
            amount = 3
        } else if (doc.productID == 3) {
            amount = 6
        }
        let nowTime = new Date().getTime()
        if (nowTime > time) {
            time = nowTime
            time = moment(nowTime).add(30 * amount, 'days').valueOf()
        } else {
            time = moment(time).add(30 * amount, 'days').valueOf()
        }
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(doc.pID)
        }, {
            $set: {
                vipTime: time,
                vipTotal: vipTotal + amount
            }
        })
    }
    return { err: 0 }
})


routes.setLogin('getChargeByDay', [
    ['day', 'number'],
], async (msg, session, cb) => {
    let { day } = msg
    let data = {}
    let docs = await mongodbHandle.chargeDao.find({ isPay: true })
    if (docs.length < 1) {
        return { err: 2 }
    }
    let total = 0
    for (let i = 0; i < docs.length; i++) {
        let doc = docs[i]
        total += doc.money
    }

    return {
        err: 0,
        data: {
            day: day,
            money: total,
            times: docs.length
        }
    }
})


routes.setLogin('transferCharge', [
    ['pID1', 'string'],
    ['pID2', 'string'],
], async (msg, session, cb) => {
    let docs = await mongodbHandle.chargeDao.find({ pID: msg.pID1, isPay: true })
    if (docs.length < 1) {
        return { err: 1 }
    }
    let total = 0, vipTotal = 0, giftTotal = 0
    for (let i = 0; i < docs.length; i++) {
        let doc = docs[i]
        total += doc.money
        if (doc.productID <= 3) {
            vipTotal += doc.money
        } else {
            giftTotal += doc.money
        }
    }
    let player1 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.pID1) })
    if (!player1) {
        return { err: 1 }
    }
    if (player1.transferCharge) {
        return { err: 0, code: 1 }
    }

    let player2 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.pID2), uID: player1.uID })
    if (!player2) {
        return { err: 0, code: 3 }
    }
    if (player2.getCharge) {
        return { err: 0, code: 2 }
    }
    await mongodbHandle.playerDao.updateOne({ pID: ObjectId(msg.pID1) }, { $set: { transferCharge: total } })
    await mongodbHandle.playerDao.updateOne({ pID: ObjectId(msg.pID2) }, { $set: { getCharge: total } })
    return { err: 0 }
})

//充值
routes.setNotLogin('notifycharge', [], async (msg, session) => {
    let {
        pid,
        orderid,
        price,
        realprice,
        orderuid,
        key
    } = msg
    console.log(msg)

})